package com.rbac.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.rbac.bean.Permission;
import com.rbac.service.PermissionService;

@Controller
public class IndexController {

	@Autowired
	private PermissionService permissionService;
	
	@RequestMapping({"/","main"})
	public ModelAndView main() {
		ModelAndView view =new ModelAndView("main");
		List<Permission> permissions=permissionService.findAll();
		Map<Integer,Permission> permissionMap=new HashMap<>(permissions.size());
		
		Permission root=null;
		for(Permission permission:permissions) {
			permissionMap.put(permission.getId(), permission);
		}
		Permission parent =null;
		for(Permission permission:permissions) {
			parent = permissionMap.get(permission.getPid());
			if(parent!=null) {
				parent.getChildren().add(permission);
			}else {
				root=permission;
			}
		}
		
		view.addObject("rootPermission",root);
		
		return view;
	}
}
